var express = require('express');
var router = express.Router();
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const fse = require('fs-extra');
const cors = require('cors');
const app = express();
app.use(cors());


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});


// 临时存储分片的目录
const UPLOAD_DIR = path.resolve(__dirname, 'upload_tmp');

// 确保临时目录存在
fse.ensureDirSync(UPLOAD_DIR);

// 配置multer处理文件上传
const upload = multer({ dest: UPLOAD_DIR });

// 处理分片上传
router.post('/upload', upload.single('file'), async (req, res) => {
  try {
    const { filename, chunkIndex, totalChunks, fileHash } = req.body;
    
    // 为每个文件创建单独的目录
    const chunkDir = path.resolve(UPLOAD_DIR, fileHash);
    await fse.ensureDir(chunkDir);
    
    // 将分片移动到对应的目录
    const chunkPath = path.resolve(chunkDir, `${chunkIndex}`);
    await fse.move(req.file.path, chunkPath);
    
    res.json({
      code: 0,
      msg: '分片上传成功',
      data: {
        chunkIndex,
        totalChunks
      }
    });
  } catch (error) {
    console.error('分片上传失败:', error);
    res.status(500).json({
      code: 1,
      msg: '分片上传失败'
    });
  }
});

// 合并分片
router.post('/merge', express.json(), async (req, res) => {
  try {
    const { filename, fileHash, totalChunks } = req.body;
    const chunkDir = path.resolve(UPLOAD_DIR,   );
    const filePath = path.resolve(UPLOAD_DIR, filename);
    
    // 检查所有分片是否已上传
    const chunkPaths = await fse.readdir(chunkDir);
    if (chunkPaths.length !== parseInt(totalChunks)) {
      return res.status(400).json({
        code: 1,
        msg: '分片数量不匹配'
      });
    }
    
    // 按分片索引排序
    chunkPaths.sort((a, b) => parseInt(a) - parseInt(b));
    
    // 创建写入流
    const writeStream = fs.createWriteStream(filePath);
    
    // 合并分片
    for (const chunkPath of chunkPaths) {
      const chunkFilePath = path.resolve(chunkDir, chunkPath);
      const buffer = await fse.readFile(chunkFilePath);
      writeStream.write(buffer);
      await fse.unlink(chunkFilePath); // 删除已合并的分片
    }
    
    writeStream.end();
    
    // 删除分片目录
    await fse.rmdir(chunkDir);
    
    res.json({
      code: 0,
      msg: '文件合并成功',
      data: {
        filename,
        url: `http://localhost:3000/uploads/${filename}`
      }
    });
  } catch (error) {
    console.error('文件合并失败:', error);
    res.status(500).json({
      code: 1,
      msg: '文件合并失败'
    });
  }
});

// 文件下载
router.get('/download/:filename', (req, res) => {
  const filePath = path.resolve(UPLOAD_DIR, req.params.filename);
  if (fs.existsSync(filePath)) {
    res.download(filePath);
  } else {
    res.status(404).send('文件不存在');
  }
});

// 检查分片上传状态
router.get('/check', async (req, res) => {
  const { fileHash } = req.query;
  const chunkDir = path.resolve(UPLOAD_DIR, fileHash);
  
  try {
    if (await fse.pathExists(chunkDir)) {
      const uploadedChunks = await fse.readdir(chunkDir);
      res.json({
        code: 0,
        data: uploadedChunks
      });
    } else {
      res.json({
        code: 0,
        data: []
      });
    }
  } catch (error) {
    console.error('检查分片状态失败:', error);
    res.status(500).json({
      code: 1,
      msg: '检查分片状态失败'
    });
  }
});


module.exports = router;